<?php

App::uses('AppController', 'Controller');

/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('*');
    }

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    /**
     * edit method
     *
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
        //$groups = $this->User->Group->find('list');
        //$this->set(compact('groups'));
    }

    /**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        /*
          if (!$this->request->is('post')) {
          throw new MethodNotAllowedException();
          }
          $this->User->id = $id;
          if (!$this->User->exists()) {
          throw new NotFoundException(__('Invalid user'));
          }
          if ($this->User->delete()) {
          $this->Session->setFlash(__('User deleted'));
          $this->redirect(array('action' => 'index'));
          }
          $this->Session->setFlash(__('User was not deleted'));
          $this->redirect(array('action' => 'index'));
          }
         */
    }

    /**
     * Common login action
     *
     * @return void
     */
    public function login() {

        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                if ($this->Auth->user()) {
                    $this->User->id = $this->Auth->user('id');
                    $this->User->saveField('last_login', date('Y-m-d H:i:s'));

                    if ($this->here == $this->Auth->loginRedirect) {
                        $this->Auth->loginRedirect = '/';
                    }

                    $this->Session->setFlash(sprintf(__d('users', '%s you have successfully logged in'), $this->Auth->user('username')));
                    if (!empty($this->request->data)) {
                        $data = $this->request->data[$this->modelClass];
                        $this->_setCookie();
                    }

                    if (empty($data['return_to'])) {
                        $data['return_to'] = null;
                    }

                    return $this->redirect($this->Auth->redirect($data['return_to']));
                } else {
                    $this->Auth->flash(__d('users', 'Invalid e-mail / password combination.  Please try again'));
                }
            } else {
                $this->Auth->flash(__d('users', 'Invalid e-mail / password combination.  Please try again'));
            }
        }
        if (isset($this->request->params['named']['return_to'])) {
            $this->set('return_to', urldecode($this->request->params['named']['return_to']));
        } else {
            $this->set('return_to', false);
        }
    }

    /**
     * Common logout action
     *
     * @return void
     */
    public function logout() {
        $user = $this->Auth->user();
        $this->Session->destroy();
        $this->Cookie->destroy();
        $this->Session->setFlash(sprintf(__d('users', '%s you have successfully logged out'), $user[$this->{$this->modelClass}->displayField]));
        $this->redirect($this->Auth->logout());
    }

    /**
     * Sets the cookie to remember the user
     *
     * @param array Cookie component properties as array, like array('domain' => 'yourdomain.com')
     * @param string Cookie data keyname for the userdata, its default is "User". This is set to User and NOT using the model alias to make sure it works with different apps with different user models across different (sub)domains.
     * @return void
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html
     */
    protected function _setCookie($options = array(), $cookieKey = 'User') {
        if (empty($this->request->data[$this->modelClass]['remember_me'])) {
            $this->Cookie->delete($cookieKey);
        } else {
            $validProperties = array('domain', 'key', 'name', 'path', 'secure', 'time');
            $defaults = array(
                'name' => 'rememberMe');

            $options = array_merge($defaults, $options);
            foreach ($options as $key => $value) {
                if (in_array($key, $validProperties)) {
                    $this->Cookie->{$key} = $value;
                }
            }

            $cookieData = array(
                'email' => $this->request->data[$this->modelClass]['email'],
                'password' => $this->request->data[$this->modelClass]['password']);
            $this->Cookie->write($cookieKey, $cookieData, true, '1 Month');
        }
        unset($this->request->data[$this->modelClass]['remember_me']);
    }

    /**
     *
     * @param type $plan 
     */
    public function newSubscribe($plan = null) {
        $this->set('title_for_layout', __('Sign up'));
        $defaultPlan = array(1, 3, 6, 12);

        if ($this->Auth->user()) {
            $this->Session->setFlash(__d('users', 'You are already registered and logged in!'));
            $this->redirect('/');
        }
        if (!empty($this->request->data)) {
            //set default member
            $this->request->data['User']['group_id'] = $this->User->Group->getIdByName(GROUP_MEMBER);
            $user = $this->User->register($this->request->data);
            if ($user !== false) {
                $this->Session->write(LASTEST_USER_SIGNUP_ID, $this->User->id);
                $plan = $this->request->data[$this->modelClass]['plan'];
                
                $subscribe = $this->User->Subscription->newSubscride($this->User->id, $plan, null, $this->request->data['User']['payment_method']);
                
                if ($this->request->data['User']['payment_method'] == PAYPAL_METHOD) {
                    //$this->_sendVerificationEmail($this->User->data, array(), PAYPAL_METHOD);
                    $this->Session->write('paypal_payment_data_' . $user[$this->modelClass]['id'], $this->request->data);
                    $this->redirect(array('action' => 'processPayment', $user[$this->modelClass]['id']));
                } else {
                    //Save payment
                     
                    $this->_sendVerificationEmail($this->User->data, array(), PICKUP_METHOD);
                    $this->Session->setFlash(__d('users', 'Your account has been created. You should receive an e-mail shortly to authenticate your account. Once validated you will be able to login. '));
                    $this->redirect(array('action' => 'login'));
                }
            } else {
                unset($this->request->data[$this->modelClass]['password']);
                unset($this->request->data[$this->modelClass]['temppassword']);
                $this->Session->setFlash(__d('users', 'Your account could not be created. Please, try again.'), 'default', array('class' => 'message warning'));
            }
        }
        if (!in_array($plan, $defaultPlan)) {
            $plan = 12;
        }
        $this->set('plan', $plan);
    }

    /**
     * Confirm email action
     *
     * @param string $type Type, deprecated, will be removed. Its just still there for a smooth transistion.
     * @param string $token Token
     * @return void
     */
    public function verify($type = 'email', $token = null) {
        if ($type == 'reset') {
            // Backward compatiblity
            $this->request_new_password($token);
        }

        try {
            $users = $this->User->verifyEmail($token);

            // Set Waiting Subscription to Padding
            $this->User->Subscription->changeStatus($users['User']['id']);
            $this->Session->setFlash(__d('users', 'Your e-mail has been validated!'));
            $this->verifyMailToAdmin($users);
            return $this->redirect(array('action' => 'login'));
        } catch (RuntimeException $e) {
            $this->Session->setFlash($e->getMessage());
            return $this->redirect('/');
        }
    }

    protected function verifyMailToAdmin($userData, $options = array()) {

        $defaults = array(
            'from' => 'info@' . env('HTTP_HOST'),
            'subject' => __('Approve supscriber'),
            'template' => 'admin_confirm_verify',
            'layout' => 'default');

        $options = array_merge($defaults, $options);


        $Email = $this->_getMailInstance();
        $Email->to(Configure::read('App.adminEmail'))
                ->from($options['from'])
                ->subject($options['subject'])
                ->template($options['template'], $options['layout'])
                ->viewVars(array(
                    'model' => $this->modelClass,
                    'user' => $userData))
                ->send();
    }

    /**
     * Reset Password Action
     *
     * Handles the trigger of the reset, also takes the token, validates it and let the user enter
     * a new password.
     *
     * @param string $token Token
     * @param string $user User Data
     * @return void
     */
    public function reset_password($token = null, $user = null) {
        if (empty($token)) {
            $admin = false;
            if ($user) {
                $this->request->data = $user;
                $admin = true;
            }
            $this->_sendPasswordReset($admin);
        } else {
            $this->_resetPassword($token);
        }
    }

    /**
     * This method allows the user to change his password if the reset token is correct
     *
     * @param string $token Token
     * @return void
     */
    protected function _resetPassword($token) {
        $user = $this->User->checkPasswordToken($token);
        if (empty($user)) {
            $this->Session->setFlash(__d('users', 'Invalid password reset token, try again.'));
            $this->redirect(array('action' => 'reset_password'));
        }

        if (!empty($this->request->data) && $this->User->resetPassword(Set::merge($user, $this->request->data))) {
            $this->Session->setFlash(__d('users', 'Password changed, you can now login with your new password.'));
            $this->redirect($this->Auth->loginAction);
        }

        $this->set('token', $token);
    }

    /**
     * Checks if the email is in the system and authenticated, if yes create the token
     * save it and send the user an email
     *
     * @param boolean $admin Admin boolean
     * @param array $options Options
     * @return void
     */
    protected function _sendPasswordReset($admin = null, $options = array()) {
        $defaults = array(
            'from' => 'noreply@' . env('HTTP_HOST'),
            'subject' => __d('users', 'Password Reset'),
            'template' => 'password_reset_request',
            'layout' => 'default');

        $options = array_merge($defaults, $options);

        if (!empty($this->request->data)) {
            $user = $this->User->passwordReset($this->request->data);

            if (!empty($user)) {

                $Email = $this->_getMailInstance();
                $Email->to($user[$this->modelClass]['email'])
                        ->from($options['from'])
                        ->subject($options['subject'])
                        ->template($options['template'], $options['layout'])
                        ->viewVars(array(
                            'model' => $this->modelClass,
                            'user' => $this->User->data,
                            'token' => $this->User->data[$this->modelClass]['password_token']))
                        ->send();


                if ($admin) {
                    $this->Session->setFlash(sprintf(
                                    __d('users', '%s has been sent an email with instruction to reset their password.'), $user[$this->modelClass]['email']));
                    $this->redirect(array('action' => 'index', 'admin' => true));
                } else {
                    $this->Session->setFlash(__d('users', 'You should receive an email with further instructions shortly'));
                    $this->redirect(array('action' => 'login'));
                }
            } else {
                $this->Session->setFlash(__d('users', 'No user was found with that email.'));
                $this->redirect($this->referer('/'));
            }
        }
        $this->render('request_password_change');
    }

    /**
     * Process Payment Method
     * 
     * @param int $id 
     */
    public function processPayment($id) {
        $this->setPageTitle(__('Process to payment'));
        $user_id = $this->Session->read(LASTEST_USER_SIGNUP_ID);
        if ($user_id == $id) {
            $this->User->id = $id;
            if (!$this->User->exists()) {
                throw new NotFoundException(__('Invalid user'));
            }
            $this->request->data = $this->User->find('first', array(
                        'conditions' => array('User.id' => $id),
                        'contain' => array('Subscription' => array(
                                'conditions' => array('Subscription.active' => SUBSCRIPTION_STATUS_WAITING_CONFIRM_EMAIL, 'Subscription.payment_method' => PAYPAL_METHOD)
                            )
                        ),
                        'recursive' => 2
                            )
            );
            $plan = $this->User->Subscription->getTerm($this->request->data['Subscription'][0]['id'], true);
            $this->set('term', $plan['SubscriptionTerm']['term']);
            $this->set('amount', $plan['SubscriptionTerm']['price']);
            
        } else {
            //throw new NotFoundException(__('Invalid user'));
            $this->redirect('/');
        }
    }

    public function modifyUserInfo($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been udated.'));
                $this->User->Subscription->updatePlan($this->request->data['User']['subs_id'], $this->request->data['User']['plan']);
                $this->redirect(array('action' => 'processPayment', $this->request->data['User']['id']));
            } else {
                $this->Session->setFlash(__('The user could not be updated. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->find('first', array(
                        'conditions' => array('User.id' => $id),
                        'contain' => array('Subscription' => array(
                                'conditions' => array('Subscription.active' => SUBSCRIPTION_STATUS_WAITING_CONFIRM_EMAIL, 'Subscription.payment_method' => PAYPAL_METHOD)
                            )
                        ),
                        'recursive' => 2
                            )
            );
            $this->set('term', $this->User->Subscription->getTerm($this->request->data['Subscription'][0]['id']));
        }
    }

    public function contactInfo($id = null) {
        if (!empty($this->request->data)) {
            
        } else {
            $this->User->id = $id;
            if (!$this->User->exists()) {
                throw new NotFoundException(__('Invalid user'));
            }
        }
    }

    public function saveSubscride() {

        if ($this->Auth->user()) {
            $this->Session->setFlash(__d('users', 'You are already registered and logged in!'));
            $this->redirect('/');
        }
        if (!empty($this->request->data)) {
            
        }
    }

    /**
     * Sends the verification email
     *
     * This method is protected and not private so that classes that inherit this
     * controller can override this method to change the varification mail sending
     * in any possible way.
     *
     * @param string $to Receiver email address
     * @param array $options EmailComponent options
     * @return boolean Success
     */
    protected function _sendVerificationEmail($userData, $options = array(), $paymentMethod = null) {
        $defaults = array(
            'from' => Configure::read('App.defaultEmail'),
            'subject' => __d('users', 'Account verification'),
            'template' => 'account_verification',
            'layout' => 'default');

        $options = array_merge($defaults, $options);
        $Email = $this->_getMailInstance();

        if ($paymentMethod != PAYPAL_METHOD) {

            $Email->to($userData[$this->modelClass]['email'])
                    ->from($options['from'])
                    ->subject($options['subject'])
                    ->template($options['template'], $options['layout'])
                    ->viewVars(array(
                        'model' => $this->modelClass,
                        'user' => $userData))
                    ->send();
        }

        // Confirm admin
        $options['template'] = 'admin_confirm_new_subscribe';
        $options['subject'] = 'A new subsciber has been registered';

        $Email->to(Configure::read('App.adminEmail'))
                ->from($options['from'])
                ->subject($options['subject'])
                ->template($options['template'], $options['layout'])
                ->viewVars(array(
                    'model' => $this->modelClass,
                    'user' => $userData,
                    'paymentMethod' => $paymentMethod
                ))
                ->send();
    }

    /**
     * Returns a CakeEmail object
     *
     * @return object CakeEmail instance
     * @link http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
     */
    protected function _getMailInstance() {
        App::uses('CakeEmail', 'Network/Email');
        return new CakeEmail();
    }

    /**
     * ADMIN SECTION
     * 
     */
    public function admin_index() {
        $this->setPageTitle(__('User Managment'));
        $this->User->recursive = 1;
        $this->paginate = array(
            'contain' => array('Group', 'Subscription')
        );
        $this->set('users', $this->paginate());
    }

    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    /**
     * add method
     *
     * @return void
     */
    public function admin_add() {
        $this->setPageTitle(__('Add User'));
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    /**
     * edit method
     *
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
        $groups = $this->User->Group->find('list');
        $this->set(compact('groups'));
    }

    /**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User waas not deleted'));
        $this->redirect(array('action' => 'index', 'admin' => true));
    }

    /**
     * Admin login method
     * 
     */
    public function admin_login() {
        $this->redirect(array('action' => 'login', 'admin' => false));
    }

    /**
     * Delegate user right
     * 
     */
    public function delegate() {
        if ($this->Auth->user('id')) {
            $group = $this->User->Group->getGroup($this->Auth->user('group_id'));

            switch ($group) {
                case GROUP_ADMIN:
                    $url = array('controller' => 'pages', 'action' => 'index', 'admin' => true);
                    break;
                case GROUP_MODERATOR:
                    $url = array('controller' => 'pages', 'action' => 'index', 'admin' => true);
                    break;
                case GROUP_MEMBER:
                default:
                    //$url = array('controller' => 'users', 'action' => 'index', 'admin' => false);
                    $url = array('controller' => 'users', 'action' => 'client', 'admin' => false);
                    break;
            }
            $this->redirect($url);
        } else {
            $this->redirect('/');
        }
    }

    public function admin_setting() {
        if ($this->Auth->user('id')) {
            $this->data = $this->User->read(null, $this->Auth->user('id'));
            $groups = $this->User->Group->find('list');
            $this->set(compact('groups'));
        } else {
            //$this->Session->setFlash(__('Please login.'));
            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }
    
    public function client () {
        $this->layout = 'client';
        $this->setPageTitle(__('Client Information'));
        //$this->User->recursive = 0;
        //$this->set('users', $this->paginate());
        $send_log = $this->User->SendLog->find('all'); pr($send_log);
	//$this->set('sendLogs', $this->paginate('SendLog'));
    }

}

